#!/bin/bash

echo "You need to manually run '\033[0;32mmvn clean package - DskipTests=true - Smaven. compile. fork=true - P prod\033[0m' in advance to start automatic publishing"

PROJECTS_DIR=$(pwd)
# 遍历每个项目目录
for dir in $(find $PROJECTS_DIR \( -name dockerfile -o -name Dockerfile \) ! -path "$PROJECTS_DIR/docker/*"); do
    # 获取目录名
    dir_name=$(dirname "$dir")

    echo "\033[0;32mBuilding and pushing Docker image for $dir_name\033[0m"

    # 进入项目目录
    cd "$dir_name" || { echo "Directory does not exist: $dir_name"; exit 1; }
    tag_name=$(basename "$dir_name")
    echo "\033[0;32mBuilding $tag_name...\033[0m"
    # 构建 Docker 镜像
    docker build -t $tag_name . || { echo "\033[0;31mDocker build command failed in $dir_name. Exiting.\033[0m"; exit 1; }

    # 返回到上一级目录
    cd "$PROJECTS_DIR"
done

echo "\033[0;32mAll Docker images built and pushed\033[0m"

echo "\033[0;32Building and pushing Docker images completed\033[0m"

# 启动 docker-compose
docker-compose up -d || { echo "\033[0;31mdocker-compose command failed. Exiting.\033[0m"; exit 1; }

echo "\033[0;32mAll script execution completed\033[0m"

exit 0;